package com.cll.printdemo;

import android.accessibilityservice.AccessibilityService;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.List;

/**
 * @author cll
 * @date :2022/12/2
 */
public class MyAccessibilityService extends AccessibilityService {
    Handler handler = new Handler(Looper.getMainLooper());
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        String packName = event.getPackageName().toString();
        //只使用界面变化的监听，避免点击事件监听进入死循环
        Log.i("进入到监听", "onAccessibilityEvent: "+packName);
        if ("com.android.printspooler".equals(packName)) {
            AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
            if (rootInActiveWindow != null) {
                List<AccessibilityNodeInfo> infos = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.android.printspooler:id/print_button");
                if (infos != null) {
                    for (int i = 0; i < infos.size(); i++) {
                        AccessibilityNodeInfo accessibilityNodeInfo = infos.get(i);
                        String content = accessibilityNodeInfo.getContentDescription().toString();
                        if ("打印".equals(content)) {
                            if (accessibilityNodeInfo.isClickable()) {
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        accessibilityNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                                    }
                                },5000);
                            }
                            break;

                        }
                    }
                }

            }
        }


        }

    @Override
    public void onInterrupt() {

    }
}
